package gui.linkFinderFrame;



import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.EventListenerList;


//import DBList.AddListener;

public class AddValuePanel extends JPanel implements ActionListener, DocumentListener {
	private static final long serialVersionUID = 1L;
	private boolean alreadyEnabled = false;
    private JButton button;
    private JTextField text=new JTextField(10);
    
	protected EventListenerList listenerList = new EventListenerList();			
        
    //Required by ActionListener.
    public void actionPerformed(ActionEvent e) {
       String name = text.getText();
            
       fireAddValueEvent(
            		new AddValueEvent(name,button.getText()));
    }

  	protected void fireAddValueEvent(AddValueEvent evt) 
  	{
           Object[] listeners = listenerList.getListenerList();
           for (int i=0; i<listeners.length; i+=2) 
            {
                if (listeners[i]==AddValueListener.class)
                {
                    ((AddValueListener)listeners[i+1]).valueEntered(evt);
                }
            }
   	}
    	
    public void addValueEventListener(AddValueListener listener) 
    {
           listenerList.add(AddValueListener.class, listener);
    }
    	
    public void removeValueEventListener(AddValueListener listener) {
           listenerList.remove(AddValueListener.class, listener);
    }

    public void setText(String str){text.setText(str);};
    
    //Required by DocumentListener.
    public void insertUpdate(DocumentEvent e) {
        enableButton();
    }

    //Required by DocumentListener.
    public void removeUpdate(DocumentEvent e) {
        handleEmptyTextField(e);
    }
    
    //Required by DocumentListener.
    public void changedUpdate(DocumentEvent e) {
        if (!handleEmptyTextField(e)) {
             enableButton();
        }
    }

    //enabling the button.
    private void enableButton() 
    {
            if (!alreadyEnabled) 
            {
                button.setEnabled(true);
            }
    }

    private boolean handleEmptyTextField(DocumentEvent e) 
    {
        if (e.getDocument().getLength() <= 0) 
        {
                button.setEnabled(false);
                alreadyEnabled = false;
                return true;
        }
            return false;        
    }

	public AddValuePanel(String name){
		this.setLayout(new FlowLayout());
		button=new JButton(name);		        
        button.setActionCommand(name);
        button.addActionListener(this);
        this.add(button);
        this.add(this.text);
        this.setVisible(true);
	}

}
